package com.neusoft.javafxdemo2.common;

import com.neusoft.javafxdemo2.entity.Supervisor;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FileUtils {
    public static Map readObject(String fileName){
        Map map = new HashMap();
        File f1 = new File(fileName);
        try {
            if (!f1.exists()) {//如果文件不存在则创建一个新文件
               return map;
            }
            FileInputStream fis = new FileInputStream(fileName);
            ObjectInputStream ois = new ObjectInputStream(fis);
            map = (Map<String, Supervisor>)ois.readObject();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return  map;
    }
    public static void writeObject(String fileName, Map map){
        //将map对象写入到supervisor.txt文件中
        File f1 = new File(fileName);
        try {
            if (!f1.exists()) {//如果文件不存在则创建一个新文件
                f1.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(f1);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(map);//写入map对象
            oos.flush();//刷新缓冲区，直接写入文件
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
